package com.tanhua.dubbo.mongo.api;

import cn.hutool.core.util.RandomUtil;
import com.tanhua.dubbo.db.api.PeachBlossomAudioApi;
import com.tanhua.model.mongo.PeachBlossomAudio;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class PeachBlossomAudioApiImpl implements PeachBlossomAudioApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存桃花传音
    public void savePeachBlossomAudio(PeachBlossomAudio audio) {
        mongoTemplate.save(audio);
    }

    //从数据库随机返回一条语音数据，排除自己的语音信息
    public PeachBlossomAudio findPeachblossom(Long userId) {

        //将mongdb里的排除自己的语音信息全部查询
        Criteria criteria = Criteria.where("tag").is(0);
        Query query = Query.query(criteria);
        List<PeachBlossomAudio> audioList = mongoTemplate.find(query, PeachBlossomAudio.class);

        //排除自己的数据,获得list集合
        List<PeachBlossomAudio> list=new ArrayList<>();

        for (PeachBlossomAudio audio : audioList) {

            if (audio.getUserId() != userId){
                list.add(audio);
            }
        }

        //随机返回一条数据
        PeachBlossomAudio peachBlossomAudio = RandomUtil.randomEle(list);

        //随机返回一条数据
       //TypedAggregation<PeachBlossomAudio> aggregation =
       //        TypedAggregation.newAggregation(PeachBlossomAudio.class, Aggregation.sample(1));

       //AggregationResults<PeachBlossomAudio> aggregate =
       //             mongoTemplate.aggregate(aggregation, PeachBlossomAudio.class);
       //List<PeachBlossomAudio> results = aggregate.getMappedResults();
       //PeachBlossomAudio audio = results.get(0);

        return peachBlossomAudio;
    }

    //因语音已被用户所获取 所以更新数据 tag为1
    public void updatePeachblossom(PeachBlossomAudio audio, int tag) {

        Query query = Query.query(Criteria.where("id").is(audio.getId()));
        Update update= new Update();
        update.set("tag",tag);
        mongoTemplate.updateFirst(query,update,PeachBlossomAudio.class);
    }
}
